import { Component, OnInit, ViewChild, ChangeDetectorRef, Inject, forwardRef } from '@angular/core';
import { AppComponent } from '../../../../app.component';

import { masterService } from '../../../../../lib/master.service';
import { saveVarService } from '../../../../../lib/saveVar.service'
import { path } from '../../../../path.config';
import { ModalDirective } from 'ngx-bootstrap/modal';
import * as moment from 'moment';

import { ExchangeCardTemplateGridComponent } from '../exchange-card-template-grid/exchange-card-template-grid.component';

@Component({
    selector: 'exchange-card-template-add',
    templateUrl: './exchange-card-template-add.component.html',
    styleUrls: ['./exchange-card-template-add.component.css'],
    providers: [forwardRef(() => AppComponent),
                forwardRef(() => ExchangeCardTemplateGridComponent)]
})
export class ExchangeCardTemplateAddComponent implements OnInit {
    @ViewChild('SearchGoodsSn') public SearchGoodsSn: ModalDirective;
    // api
    // 表格数据
    public createItem: any = path.cardManagement.cardTemplate.createItem;
    public listShipping: any = path.cardManagement.cardTemplate.listShipping;
    public getGoodsInfo: any = path.cardManagement.cardTemplate.getGoodsInfo;
    public listExchangeCardRegion: any = path.cardManagement.cardTemplate.listExchangeCardRegion;
    // 添加活动商品时查询商品信息列表
    private goodsSninfo = path.campaignManage.activityGoods.goodsSninfo;

    // 列表项数组
    public rows: Array<any> = [];
    // 表格数据头部标题
    public columns: Array<any> = [
        { title: '商品Sn', name: '' },
        { title: '商品名称', name: '' },
        { title: '操作', name: '' },
    ];
    // 当前页码
    public page: any = 1;
    // 一共多少页
    public itemsPerPage: number = 10;
    // 分页最多显示的页数
    public maxSize: number = 5;
    // 总页数计数变化时，事件数等于总页数计数
    public numPages: number = 1;
    // 总共的列表项数
    public totalItems: number = 0;
    // 分页器的文本配置
    public localText = {
        firstBtn: '首页',
        lastBtn: '末页',
        previousBtn: '上一页',
        nextBtn: '下一页'
    }

    public shippings = [];
    public provinces = [];
    public cities = [];
    public regions = [];
    public isShowRegion = false;
    public isDisabledAdd = true;
    public template = {
        name: '',
        enableTime: '',
        deadlineTime: '',
        goodsSn: '',
        goodsName: '',
        shippings: [],
        regions: [],
        shipping: '',
        region: ''
    };
    public region = {
        province: '',
        city: ''
    }

    constructor(public _masterService: masterService,
        public _saveVar: saveVarService,
        public cdRef: ChangeDetectorRef,
        @Inject(forwardRef(() => AppComponent)) public app: AppComponent) { }

    ngOnInit() {
        // 获取配送方式
        this._masterService.getData(this.listShipping)
        .subscribe(res => {
            if (res.statusCode == 200) {
                this.shippings = res.data;
                this.cdRef.detectChanges();
            } else if (res.statusCode == 401) {
                this.app.logOff();
            } else {
                this.app.toastError('错误信息： ' + res.errorMessage);
            }
        });
        // 获取配送区域省
        let urlParams = {
            parentId: 1
        }
        this._masterService.getData(this.listExchangeCardRegion, urlParams)
        .subscribe((res) => {
            if (res.statusCode == 200) {
                this.provinces = res.data;
            } else if (res.statusCode == 401) {
                this.app.logOff();
            } else {
                this.app.toastError('错误信息： ' + res.errorMessage);
            }
        });
    }

    public onChangeTable(page: any = {
        itemsPerPage: this.itemsPerPage,
        page: this.page
    }): any {
        // get传入的参数
        let urlObject = {
            keyword: this.template.goodsSn,
            pageSize: page.itemsPerPage,
            pageIndex: page.page
        }
        this._masterService
            .getData(this.goodsSninfo, urlObject)
            .subscribe((res) => {
                if (res.statusCode == 200) {
                    this.rows = res.data.items;
                    this.totalItems = res.data.pagination.totalCount;
                    this.itemsPerPage = res.data.pagination.pageSize;
                    this.page = parseInt(res.data.pagination.pageIndex);
                    this.cdRef.detectChanges();
                } else if (res.statusCode == 401) {
                    this.app.logOff();
                } else {
                    this.app.toastError('错误信息： ' + res.errorMessage);
                }
            })
    }

    saveAdd() {
        // 前端验证
        this.template.enableTime = $('#startTime').val() + '';
        this.template.deadlineTime = $('#endTime').val() + '';

        if (!this.template.name) {
            this.app.toastWarning('请填写模板名称！');
            return;
        } else if (!this.template.goodsSn || !this.template.goodsName) {
            this.app.toastWarning('请填写商品sn！');
            return;
        } else if (!this.template.enableTime || !this.template.deadlineTime) {
            this.app.toastWarning('请填写有效期区间！');
            return;
        } else if (this.template.shippings.length == 0) {
            this.app.toastWarning('请选择配送方式！');
            return;
        } else if (this.template.shippings.indexOf("3") != -1 && this.template.regions.length == 0) {
            this.app.toastWarning('请选择配送省市！');
            return;
        }
        this.template.shipping = this.template.shippings.toString();
        this.template.region = this.template.regions.toString();
        this._masterService.postData(this.createItem, this.template)
        .subscribe((res) => {
            if (res.statusCode == 200) {
                this.app.toastSuccess('添加成功！');
                this._masterService.closeCardTemplate.emit();
                this._masterService.CardTemplateReload.emit();
            } else if (res.statusCode == 401) {
                this.app.logOff();
            } else {
                this.app.toastError('错误信息： ' + res.errorMessage);
            }
        });
    }

    selectShipping(code) {
        if (this.template.shippings.indexOf(code) == -1) {
            if (code == 3) {
                this.isShowRegion = true;
            }
            this.template.shippings.push(code);
        }
        else {
            if (code == 3) {
                this.isShowRegion = false;
                this.isDisabledAdd = true;
                this.region = {
                    province: '',
                    city: ''
                }
                this.template.regions = [];
                this.listRegions();
            }
            this.template.shippings.splice(this.template.shippings.indexOf(code), 1);
        }
        this.cdRef.detectChanges();
    }
    
    changeProvince() {
        this.isDisabledAdd = true;
        this.region.city = '';
        // 获取配送区域省
        let urlParams = {
            parentId: this.region.province
        }
        this._masterService.getData(this.listExchangeCardRegion, urlParams)
        .subscribe((res) => {
            if (res.statusCode == 200) {
                this.cities = res.data;
                this.cdRef.detectChanges();
            } else if (res.statusCode == 401) {
                this.app.logOff();
            } else {
                this.app.toastError('错误信息： ' + res.errorMessage);
            }
        });
    }

    changeCity() {
        if (this.region.city != '') {
            this.isDisabledAdd = false;
        } else {
            this.isDisabledAdd = true;
        }
        this.cdRef.detectChanges();
    }

    addRegion() {
        if (this.template.regions.indexOf(this.region.city) == -1) {
            this.template.regions.push(this.region.city);
            this.listRegions();
        } else {
            this.app.toastWarning('不可重复选择');
        }
    }

    deleteRegion(regionId) {
        this.template.regions.splice(this.template.regions.indexOf(regionId), 1);
        this.listRegions();
    }

    listRegions() {
        if (this.template.regions.length == 0) {
            this.regions = [];
            this.cdRef.detectChanges();
            return;
        }
        // 获取配送区域省
        let urlParams = {
            ids: encodeURIComponent(this.template.regions.toString())
        }
        this._masterService.getData(this.listExchangeCardRegion, urlParams)
        .subscribe((res) => {
            if (res.statusCode == 200) {
                this.regions = res.data;
                this.regions.forEach(row => {
                    let val = row.pathName.split('/');
                    row.province = val[1];
                    row.city = val[2];
                })
                this.cdRef.detectChanges();
            } else if (res.statusCode == 401) {
                this.app.logOff();
            } else {
                this.app.toastError('错误信息： ' + res.errorMessage);
            }
        });
    }

    searchSn() {
        this.SearchGoodsSn.show();
        this.onChangeTable();
    }

    selectGoods(row) {
        this.SearchGoodsSn.hide();
        this.template.goodsName = row.goodsName;
        this.template.goodsSn = row.goodsSn;
    }
}
